# -*- coding: UTF-8 -*-
# Copyright 2020 YangZhongxi
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and

import os
from PyQt5 import QtCore
import time
import queue


class AsyncDataReceiver(QtCore.QThread):
    dataListener = QtCore.pyqtSignal(str)
    isRun = False
    dataQueue = queue.Queue()  # 队列，用于存储实时数据
    mutex = QtCore.QMutex()

    def __init__(self, filename):
        super(AsyncDataReceiver, self).__init__()
        self.DataBuffer = []
        self.isRun = True

    def Start(self):
        self.isRun = True
        self.start() # 开启线程

    def Stop(self):
        self.isRun = False # 将纯种标志位设为false，以便线程退出循环
        self.exit()

    def AddData(self, data):  # 添加数据， 因为dataQueue是多线程访问，需要加锁
        d = object()
        d.data = data
        d.time = time.time()
        self.mutex.lock()  # 加锁
        self.dataQueue.put(d)  # 将数据放到队列中
        self.mutex.unlock()  # 解锁

    def onWork(self):  # 侦听业务处理函数，将队列中的所有数据都存入文件，并
        str = ""
        while self.dataQueue.qsize() > 0:  # 将队列中所有数据组成一个字符串，通过信号发射出去
            data = self.dataQueue.get()
            str += time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(data.time)) + " " + data.data  + "\n"
        if(len(str) > 0):
            self.dataListener.emit(str) # 将字符串数据抛出

    def run(self):
        while self.isRun:
            time.sleep(0.1)
            self.mutex.lock()  # 加锁
            self.onWork()
            self.mutex.unlock()  # 解锁

    def __del__(self):
        print("线程销毁")
